// src/components/PrivateRoute.jsx
import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import { SpinLoading } from 'antd-mobile';

const PrivateRoute = ({ children }) => {
  const { isAuthenticated, checkAuth } = useAuthStore();
  const location = useLocation();
  const [checking, setChecking] = React.useState(true);
  
  React.useEffect(() => {
    const authenticate = async () => {
      await checkAuth();
      setChecking(false);
    };
    authenticate();
  }, [checkAuth]);

  if (checking) {
    return (
      <div className="flex justify-center items-center h-screen">
        <SpinLoading color="primary" />
      </div>
    );
  }

  if (!isAuthenticated) {
    // Redirect to login page if not authenticated
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return children;
};

export default PrivateRoute;